import hashlib
import json
import datetime
from bot.enterprise_wechat_gpt.util.tair_util import tair_util
# AB测试分流器

# 2:8的比例
ratio = 1  # 表示2/10的请求调用function_1，9/10的请求调用function_2


def string_hash(string):
    encoded_string = string.encode()
    hashed_string = hashlib.sha256(encoded_string)
    unique_number = int(hashed_string.hexdigest(), 16)
    return unique_number


def distribute(id, r=ratio):
    # 使用哈希值来决定函数调用
    hash_value = string_hash(id)
    # 取绝对值并对10取模，确保在1到10的范围内
    return abs(hash_value) % 10 < r


def save_A_or_B(userId, customerId, wxId, flag):
    now = datetime.datetime.now()
    j = {'userId': userId, 'customerId': customerId, 'wxId': wxId, 'flag': flag,
         'first_time': now.strftime('%Y-%m-%d %H:%M:%S')}
    tair_util.hsetnx('QW:ABTest:' + now.strftime('%Y-%m-%d'), wxId, json.dumps(j))


def get_all_ab_user(date):
    return tair_util.exhvals("QW:ABTest:" + date)


if __name__ == '__main__':
    # save_A_or_B("JDJR_648259", "K600508328717039543032", "wmTT-TEAAAT4l_3M_YvZ-roZQ2z7KGcw", "A")
    # 随机生成100个id
    import random
    import string
    ids = []
    for i in range(100):
        id = ''.join(random.sample(string.ascii_letters + string.digits, 32))
        ids.append(id)

    a, b, c = 0, 0, 0
    for id in ids:
        if distribute(id, 5):
            if distribute(id, 2):
                print(id, "A")
                a += 1
            else:
                print(id, "B")
                b += 1
        else:
            print(id, "C")
            c += 1
    print(a, b, c)